package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.MessageInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.service.MessageService;
import com.example.demo.util.ConstVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageService messageService;
    
    @PostMapping("/add")
    public AjaxResult addMessage(@RequestParam String content,
                                @RequestParam Integer pid,
                                @RequestParam Integer receiverId,
                                @RequestParam(required = false) Integer parentId,
                                HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "请先登录");
        }
        
        MessageInfo message = new MessageInfo();
        message.setContent(content);
        message.setPid(pid);
        message.setSenderId(userInfo.getId());
        message.setReceiverId(receiverId);
        message.setParentId(parentId);
        
        boolean success = messageService.addMessage(message);
        return success ? AjaxResult.success("留言成功") : AjaxResult.fail("留言失败");
    }
    
    @GetMapping("/get-all")
    public AjaxResult getProductMessages(@RequestParam Integer pid) {
        List<MessageInfo> messages = messageService.getProductMessages(pid);
        return AjaxResult.success(messages);
    }
    
    @GetMapping("/my-received")
    public AjaxResult getMyReceivedMessages(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "请先登录");
        }
        
        List<MessageInfo> messages = messageService.getReceivedMessages(userInfo.getId());
        return AjaxResult.success(messages);
    }
    
    @PostMapping("/delete")
    public AjaxResult deleteMessage(@RequestParam Integer id, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "请先登录");
        }
        
        boolean success = messageService.updateMessageStatus(id, 0);
        return success ? AjaxResult.success("删除成功") : AjaxResult.fail("删除失败");
    }
} 